package initialize

import (
	"fmt"
	"portal_api/global"
	"portal_api/validators"
	"reflect"
	"strings"

	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	en_translations "github.com/go-playground/validator/v10/translations/en"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
)

// InitTrans 初始化翻译器
func InitTrans(locale string) {

	// 修改gin框架中的Validator引擎属性，实现自定义
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		// 注册获取json的tag的自定义方法,修改为传递参数的tag（xxxx.Password: -> xxxx.password:）
		v.RegisterTagNameFunc(func(fld reflect.StructField) string {
			name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0]
			if name == "" {
				name = strings.SplitN(fld.Tag.Get("form"), ",", 2)[0]
			}
			if name == "" {
				name = strings.SplitN(fld.Tag.Get("uri"), ",", 2)[0]
			}
			if name == "-" {
				return ""
			}
			return name
		})
		zhTrans := zh.New()
		enTrans := en.New()
		// 第一个是默认的，后面是备选的
		uni := ut.New(enTrans, enTrans, zhTrans)
		// locale通常取决于http请求头的"Accept-Language"
		global.Trans, ok = uni.GetTranslator(locale)
		if !ok {
			panic(fmt.Sprintf("uni.GetTranslator(%s) failed", locale))
		}
		switch locale {
		case "en":
			en_translations.RegisterDefaultTranslations(v, global.Trans)
		case "zh":
			zh_translations.RegisterDefaultTranslations(v, global.Trans)
		default:
			en_translations.RegisterDefaultTranslations(v, global.Trans)
		}
		return
	}
	panic("binding.Validator.Engine().(*validator.Validate) failed")
}

// InitValidators 初始化验证器
func InitValidators() {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterValidation("mx_mobile", validators.MobileValidation)
		v.RegisterTranslation("mx_mobile", global.Trans, func(ut ut.Translator) error {
			return ut.Add("mx_mobile", "{0}必须是大陆手机号码", true)
		}, func(ut ut.Translator, fe validator.FieldError) string {
			t, _ := ut.T("mx_mobile", fe.Field())
			return t
		})
	}
}
